//
//  BookListViewController.swift
//  手账
//
//  Created by zhuxiaoxiang on 2018/12/18.
//  Copyright © 2018年 zhuxiaoxiang. All rights reserved.
//

import UIKit

class BookListViewController: BaseViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    fileprivate var data: Array<Any> = []
    
    var moneyType: String = "0" // 0代表支出
    {
        didSet {
            if moneyType == "0" {
                self.moneyTypeDescription = "expend"
            }else {
                self.moneyTypeDescription = "income"
            }
        }
    }
    
    var moneyTypeDescription: String = "income"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configBackItem()
    }
    
    override func config() {
        super.config()
        self.tableView.register(UINib(nibName: "BookListCell", bundle: nil), forCellReuseIdentifier: "CELL")
        self.tableView.estimatedRowHeight = 80
        self.tableView.separatorStyle = .none
        requestData()
    }

}

extension BookListViewController {
    func requestData() {
        XXHUD.sharedInstance.showLoading(self.view)
        let query = BmobQuery.init(className: "Book")
        query?.findObjectsInBackground({ (data, error) in
            XXHUD.sharedInstance.hide(self.view)
            self.dealWithData(data)
        })
    }
    
    func dealWithData(_ data: Array<Any>?) {
        self.data.removeAll()
        guard let data = data else {
            return
        }
        for d in data {
            let author = (d as! BmobObject).object(forKey: "author")
            let moneytype = (d as! BmobObject).object(forKey: "moneytype")
            if (author as? String) != AppUser.sharedInstance.phone || (moneytype as? String) != self.moneyTypeDescription {
                continue
            }
            self.data.append(d)
        }
        self.tableView.reloadData()
    }
}

extension BookListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CELL", for: indexPath) as! BookListCell
        cell.selectionStyle = .none
        cell.bmobObject = self.data[indexPath.row] as? BmobObject
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
}
